import numpy as np
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split


def digit_predict(train_image, train_label, test_image):
    '''
    实现功能：训练模型并输出预测结果
    :param train_sample: 包含多条训练样本的样本集，类型为ndarray,shape为[-1, 8, 8]
    :param train_label: 包含多条训练样本标签的标签集，类型为ndarray
    :param test_sample: 包含多条测试样本的测试集，类型为ndarry
    :return: test_sample对应的预测标签
    '''

    train_new_shape = (
        train_image.shape[0], train_image.shape[1]*train_image.shape[2])
    test_new_shape = (test_image.shape[0],
                      test_image.shape[1]*test_image.shape[2])
    train_image.resize(train_new_shape)
    test_image.resize(test_new_shape)
    print(train_image.shape)
    md = LogisticRegression(max_iter=20000, C=0.2)
    md.fit(train_image, train_label)
    return md.predict(test_image)


if __name__ == '__main__':
    with open('逻辑回归\第5关：手写数字识别.py', encoding="utf8") as f:
        code = f.read()
        has_print_answer = False
        has_open_file = False

        if 'open' in code:
            has_open_file = True

        hash_name = ['正', '确', '率', '已', '超', '过', '0', '.', '9', '7', '！']
        hash_count = np.zeros(len(hash_name))
        for i, name in enumerate(hash_name):
            if hash_name[i] in code:
                hash_count[i] = 1
        if hash_count.sum() == len(hash_name):
            has_print_answer = True

        has_print_answer = False
        has_open_file = False

        if has_print_answer:
            print('你可能正在试图作弊，请不要这样做')
        elif has_open_file:
            print('你正在试图打开文件，请不要这样做')
        else:
            iris = datasets.load_digits()
            X = iris.images
            y = iris.target
            X_train, X_test, y_train, y_test = train_test_split(
                X, y, test_size=0.2, random_state=1)
            predict = digit_predict(X_train, y_train, X_test)
            acc = accuracy_score(y_test, predict)
            if acc > 0.97:
                print('正确率已超过0.97！')
            else:
                print('您的正确率为:%f，请继续努力！' % acc)
